package com.example.assignment01_javaee.Utils;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

/**
 * Jwt工具类
 */

public class JwtUtil {
    // 有效期为一个小时
    public static final Long JWT_TTL = 60*60*1000L;
    // 设置密钥明文
    public static final String JWT_KEY = "liran";

    // 创建token
    public static String createToken(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .claim("role","user")
                .setSubject("javaee2024")
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TTL))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,JWT_KEY)
                .compact();

        return jwtToken;
    }

    // 封装验证token是否过期的方法
    public static boolean checkToken(String token){
        if(token == null || token.isEmpty()){
            System.out.println("token为null/empty");
            return false;//过期
        }
        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(JWT_KEY).parseClaimsJws(token);
        } catch (Exception e){
            System.out.println(e.getMessage());
            return false;//过期
        }
        return true;
    }
}
